//
//  MessageHomeVC.m
//  MyProject
//
//  Created by jiaming yan on 2018/3/2.
//  Copyright © 2018年 yanjiaming. All rights reserved.
//

#import "MessageHomeVC.h"
#import "MessageHomeTableViewCell.h"
#import "MessageListVC.h"
#import <Hyphenate/Hyphenate.h>
#import "EaseConvertToCommonEmoticonsHelper.h"
#import "EaseEmotionManager.h"
#import "EaseMessageViewController.h"
#import "AppDelegate.h"
#import "NSUDManager.h"

@interface MessageHomeVC ()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic)  NSMutableArray *arrData;
@property (strong, nonatomic)  NSMutableArray *messageArrData;

@property (weak, nonatomic) IBOutlet UILabel *unReadCountLabel1;
@property (weak, nonatomic) IBOutlet UILabel *unReadCountLabel2;
@property (weak, nonatomic) IBOutlet UILabel *unReadCountLabel3;
@end

@implementation MessageHomeVC
-(void)refreshMessage{
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    /**获取未读消息*/
    [YJMSendRequest postDataWithParameters:@{} url:@"user/getUserMessageUnreadCount" result:^(NSDictionary *result, NSError *error) {
        result = [CommonUtils decryptDicWithResult:result];
        [self hideProgress:self.view animated:YES];
        if([result[@"result"] integerValue] == 1)
        {
            self.unReadCountLabel1.text = [NSString stringWithFormat:@"%@",result[@"data"][@"MESSAGE_TYPE_CANDIDATE"]];
            self.unReadCountLabel2.text = [NSString stringWithFormat:@"%@",result[@"data"][@"MESSAGE_TYPE_INCUMBENT"]];
            self.unReadCountLabel3.text = [NSString stringWithFormat:@"%@",result[@"data"][@"MESSAGE_TYPE_SYSTEM"]];
            NSInteger total = [self.unReadCountLabel1.text integerValue] + [self.unReadCountLabel2.text integerValue] +[self.unReadCountLabel3.text integerValue] ;
            if ([result[@"data"][@"MESSAGE_TYPE_CANDIDATE"] integerValue] == 0) {
                self.unReadCountLabel1.hidden = YES;
            }else{
                self.unReadCountLabel1.hidden = NO;
            }
            
            if ([result[@"data"][@"MESSAGE_TYPE_INCUMBENT"] integerValue] == 0) {
                self.unReadCountLabel2.hidden = YES;
            }else{
                self.unReadCountLabel2.hidden = NO;
            }
            
            if ([result[@"data"][@"MESSAGE_TYPE_SYSTEM"] integerValue] == 0) {
                self.unReadCountLabel3.hidden = YES;
            }else{
                self.unReadCountLabel3.hidden = NO;
            }

            if (total>  0) {
                [(UITabBarItem *)(((AppDelegate *)[UIApplication sharedApplication].delegate).tabbarController.viewControllers[2].tabBarItem) setBadgeValue:[NSString stringWithFormat:@"%zd",total]];
            }else{
                [(UITabBarItem *)(((AppDelegate *)[UIApplication sharedApplication].delegate).tabbarController.viewControllers[2].tabBarItem) setBadgeValue:nil];
            }
            
        }else{
            
            
            [CommonUtils showToast:[result objectForKey:@"msg"]];
        }
        
    }];
    




    NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
    NSArray* data = [conversations sortedArrayUsingComparator:
                     ^(EMConversation *obj1, EMConversation* obj2){
                         EMMessage *message1 = [obj1 latestMessage];
                         EMMessage *message2 = [obj2 latestMessage];
                         if(message1.timestamp > message2.timestamp) {
                             return(NSComparisonResult)NSOrderedAscending;
                         }else {
                             return(NSComparisonResult)NSOrderedDescending;
                         }
                     }];
    
    
    
    self.messageArrData = [NSMutableArray array];
    NSMutableArray *idArr = [NSMutableArray array];
    /**对消息排序处理*/
    for (NSInteger i = 0; i<data.count; i++) {
        EMConversation *model = data[i];
        if (model.latestMessage.direction == EMMessageDirectionSend) {
            if ([model latestMessage].to) {
               [idArr addObject:[NSNumber numberWithInteger:[[model latestMessage].to integerValue]]];
                [self.messageArrData addObject:model];
            }else{
                
            }
        }else{
            if ([model latestMessage].from) {
                [idArr addObject:[NSNumber numberWithInteger:[[model latestMessage].from integerValue]]];
                [self.messageArrData addObject:model];
            }else{

            }
            
        }
        
    }
    if (idArr.count > 0) {
        __weak typeof(self) weakSelf = self;
//        [self showProgressWithView:self.view animated:YES];
        /**获取用户头像*/
        [YJMSendRequest postDataWithParameters:@{@"userIds":idArr} url:@"user/batchGetIMUserInfo" result:^(NSDictionary *result, NSError *error) {
            result = [CommonUtils decryptDicWithResult:result];
            [self hideProgress:self.view animated:YES];
            if([result[@"result"] integerValue] == 1)
            {
                weakSelf.arrData = [NSMutableArray arrayWithArray:result[@"data"]];
                [weakSelf.tableView reloadData];
                
            }else{
                
                
                [CommonUtils showToast:[result objectForKey:@"msg"]];
            }
            
        }];
    }
    
    /**如果环信断开，自动登录环信*/
    UserModel *user = [NSUDManager currentUser];
    if(![[EMClient sharedClient] isConnected]){
        [[EMClient sharedClient] loginWithUsername:user.userId
                                          password:user.userId
                                        completion:^(NSString *aUsername, EMError *aError) {
                                            if (!aError) {
                                                SaintiLog(@"成功");
                                            } else {
                                                SaintiLog(@"失败");
                                            }
                                        }];
    }else{
       
    }
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
}
-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"消息";
    self.navigationItem.leftBarButtonItems = nil;
    [self loadTabbleView];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshMessage) name:@"refreshMessage" object:nil];
//
//    __weak typeof(self) weakSelf = self;
//    //        [self showProgressWithView:self.view animated:YES];
//    [YJMSendRequest postDataWithParameters:@{} url:@"common/getAlipayAccountAuthSign" result:^(NSDictionary *result, NSError *error) {
//        result = [CommonUtils decryptDicWithResult:result];
//        [self hideProgress:self.view animated:YES];
//        if([result[@"result"] integerValue] == 1)
//        {
//
//
//        }else{
//
//
//            [CommonUtils showToast:[result objectForKey:@"msg"]];
//        }
//
//    }];
}

/*
 方法描述:
 加载列表
 
 参数说明:
 <#参数说明#>
 
 返回结果:
 <#返回结果#>
 
 */
-(void)loadTabbleView{
    [self.tableView registerNib:[UINib nibWithNibName:@"MessageHomeTableViewCell" bundle:nil] forCellReuseIdentifier:@"MessageHomeTableViewCell"];
    self.tableView.tableFooterView = [[UIView alloc]init];
    self.tableView.estimatedRowHeight = 184.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
    }
}
#pragma mark ------tableView代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.arrData.count;
}

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    return 65;
//}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    static NSString *identifier = @"MessageHomeTableViewCell";
    MessageHomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    cell.selectionStyle =  UITableViewCellSelectionStyleNone;
    NSDictionary *model = self.arrData[indexPath.row];
    EMConversation *message = self.messageArrData[indexPath.row];
    
    [cell.userHeadImageView sd_setImageWithURL:[NSURL URLWithString:ImageURL(model[@"headImg"])] placeholderImage:IMAGE(@"默认图")];
    cell.nameLabel.text = model[@"nickName"];
    cell.countLabel.text = [NSString stringWithFormat:@"%d",message.unreadMessagesCount];
    if (message.unreadMessagesCount == 0) {
        cell.countLabel.hidden = YES;
    }else{
        cell.countLabel.hidden = NO;
    }
    cell.timeLabel.text = [CommonUtils messageTimeIntervalWithDate:message.latestMessage.timestamp];;
    
    if (message.latestMessage.body.type == EMMessageBodyTypeText) {
        NSString *latestMessageTitle = @"";
        NSString *didReceiveText = [EaseConvertToCommonEmoticonsHelper
                                    convertToSystemEmoticons:((EMTextMessageBody *)message.latestMessage.body).text];
        latestMessageTitle = didReceiveText;
        if ([message.latestMessage.ext objectForKey:MESSAGE_ATTR_IS_BIG_EXPRESSION]) {
            latestMessageTitle = @"[动画表情]";
        }
        cell.contentLabel.text = latestMessageTitle;
    }else if (message.latestMessage.body.type == EMMessageBodyTypeImage){
        cell.contentLabel.text = @"[图片]";
    }else if (message.latestMessage.body.type == EMMessageBodyTypeVoice){
        cell.contentLabel.text = @"[语音]";
    }else{
        
    }
    
    cell.userDetailLabel.hidden = YES;

    return cell;
    
}


- (void )tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    [CommonUtils gotoChatViewControllerWithUserName:self.arrData[indexPath.row][@"nickName"] user_id:[NSString stringWithFormat:@"%@",self.arrData[indexPath.row][@"userId"]] vc:self];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)messageListClick:(UIButton *)sender {
    MessageListVC *vc = [[MessageListVC alloc]init];
    vc.hidesBottomBarWhenPushed = YES;
    vc.messageType = sender.tag;
    [self.navigationController pushViewController:vc animated:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
